<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品列表</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>商品列表</h1>
        <nav>
            <a href="index.html">首页</a>
            <a href="product-list.html">商品列表</a>
            <a href="user.html">用户中心</a>
        </nav>
    </header>

    <main>
        <section class="product-list">
            <div class="search-bar">
                <input type="text" id="search-input" placeholder="搜索商品名称...">
                <button onclick="searchProducts()">搜索</button>
            </div>

            <div id="product-list-container">
                <!-- 商品列表将通过JS动态加载 -->
            </div>

            <div class="pagination" id="pagination">
                <!-- 分页控件将通过JS动态加载 -->
            </div>
        </section>
    </main>

    <footer>
        <p>© 2025 电商平台</p>
    </footer>

    <script src="api.js"></script>
    <script>
        let currentPage = 1;
        const pageSize = 8;
        let currentSearchParams = {};

        document.addEventListener('DOMContentLoaded', function() {
            loadProducts(currentPage);
        });

        function loadProducts(page) {
            // 显示加载状态
            const container = document.getElementById('product-list-container');
            container.innerHTML = '<div class="loading">加载商品中...</div>';

            // 调用真实API
            getProductList(page, pageSize, currentSearchParams).then(result => {
                if (result.data && result.data.records) {
                    renderProductList(result.data.records);
                    renderPagination(result.data.current, result.data.size, result.data.total);
                } else {
                    throw new Error('商品数据格式错误');
                }
            }).catch(error => {
                console.error('加载商品失败:', error);
                handleApiError(error);
                container.innerHTML = '<div class="error-message">加载商品失败，请刷新页面重试</div>';
            });
        }

        function renderProductList(products) {
            const container = document.getElementById('product-list-container');
            if (!products || products.length === 0) {
                container.innerHTML = '<div class="no-products">暂无商品</div>';
                return;
            }

            container.innerHTML = products.map(product => `
                <div class="product-item">
                    <div class="product-image-url">
                        <label>图片链接:</label>
                        <p class="image-url">${product.productImg || 'https://via.placeholder.com/300x200'}</p>
                    </div>
                    <h3>${product.productName || '未知商品'}</h3>
                    <p class="price">¥${(product.price || 0).toFixed(2)}</p>
                    <p class="description">${product.productDesc || '暂无描述'}</p>
                    <div class="product-actions">
                        <a href="product-detail.html?id=${product.id}" class="btn-secondary">查看详情</a>
                    </div>
                </div>
            `).join('');
        }

        function renderPagination(current, size, total) {
            const totalPages = Math.ceil(total / size);
            const pagination = document.getElementById('pagination');

            if (totalPages <= 1) {
                pagination.innerHTML = '';
                return;
            }

            let paginationHTML = '';

            // 上一页
            if (current > 1) {
                paginationHTML += `<button onclick="goToPage(${current - 1})">上一页</button>`;
            }

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === current) {
                    paginationHTML += `<button class="current">${i}</button>`;
                } else {
                    paginationHTML += `<button onclick="goToPage(${i})">${i}</button>`;
                }
            }

            // 下一页
            if (current < totalPages) {
                paginationHTML += `<button onclick="goToPage(${current + 1})">下一页</button>`;
            }

            pagination.innerHTML = paginationHTML;
        }

        function goToPage(page) {
            currentPage = page;
            loadProducts(page);
        }

        function searchProducts() {
            const searchTerm = document.getElementById('search-input').value.trim();

            // 更新搜索参数
            if (searchTerm) {
                currentSearchParams = {
                    productName: searchTerm
                };
            } else {
                currentSearchParams = {};
            }

            // 重置到第一页并重新加载
            currentPage = 1;
            loadProducts(currentPage);
        }

        // 搜索框回车事件
        document.addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && document.activeElement.id === 'search-input') {
                searchProducts();
            }
        });
    </script>
</body>
</html>